package com.sp.inputstream_;

import com.sp.outputstream_.Dog;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * 反序列化
 */
public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //指定反序列化的文件
        String filePath = "d:\\development\\code\\IO_Test\\news\\data.dat";

        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filePath));

        //读取
        //1. 读取(反序列化)的顺序需要和保存数据(序列化)的顺序一致
        //2. 否则会出现异常
        System.out.println(objectInputStream.readInt());
        System.out.println(objectInputStream.readBoolean());
        System.out.println(objectInputStream.readChar());
        System.out.println(objectInputStream.readDouble());
        System.out.println(objectInputStream.readUTF());
//        System.out.println(objectInputStream.readObject());
        Object dog = objectInputStream.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println("dog信息=" + dog);//底层Object -> dog

        //重要细节
        //1. 如果我们希望调用Dog的方法, 需要向下转型
        //2. 需要我们将Dog类的定义, 放到可以引用的位置
        Dog dog2 = (Dog) dog;
        System.out.println(dog2.getName());

        //关闭流, 关闭外层流即可, 底层会关闭FileInputStream流
        objectInputStream.close();
    }
}
